<template>
  <q-page class="q-pa-md">
    <div class="row items-center">
      <div class="q-pb-md text-h5">
        {{pageTitle}}
      </div>
      <q-space></q-space>
      <search-bar-toggle-btn v-model="searchBarVisibility"></search-bar-toggle-btn>
    </div>
    <div class="q-pa-sm shadow-2 q-mb-md items-center" v-show="searchBarVisibility">
      <q-btn-toggle v-model="fpsReq.msgType" :options="$d.listOptions" toggle-color="primary" :ripple="false"
        unelevated class="primary-color-border" color="white" text-color="primary" no-caps
        @click="loadListData()"></q-btn-toggle>
    </div>
    <div class="shadow-2">
      <q-table :columns="fpsInfo.columnsInfo" :rows="$d.tableData" :hide-pagination="true"
        :loading="listDataLoadingState" v-model:pagination="fpsInfo.paginationInfo"
        :visible-columns="fpsInfo.visibleColumns" selection="multiple" v-model:selected="$d.selectedItems"
        @request="fpsAssist.onDataTableRequest" row-key="msgUuid"
        @row-dblclick="onRowDblClick" binary-state-sort color="primary" dense flat separator="cell">
        <template v-slot:top="props">
          <!--功能按钮-->
          <div class="q-gutter-sm">
            <q-btn :disable="$d.tableData.length === 0 || workingStateMarkAllMsgRead" @click="markAllMsgRead" no-caps
              color="primary" :label="$t('全部标记已读')" :loading="workingStateMarkAllMsgRead" />
            <q-btn :disable="$d.selectedItems.length === 0" @click="deleteMessages" color="red" no-caps
              :label="$t('删除选中消息')"/>
            <q-btn :disable="$d.tableData.length === 0" @click="deleteReadAndHandleMessages" no-caps
              color="red" :label="$t('清空已读并已处理的消息')" />
          </div>
          <!--填充所有剩余空间-->
          <q-space />
          <table-col-options-cfg v-model:table-columns="fpsInfo.columnsInfo"
            v-model:visible-columns="fpsInfo.visibleColumns"
            @update-col-options-for-save="fpsAssist.saveColOptions"></table-col-options-cfg>
          <!--右上角全屏按钮-->
          <q-btn :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'"
            :title="props.inFullscreen ? $t('退出全屏') : $t('全屏显示')" @click="props.toggleFullscreen" class="q-ml-sm" dense
            flat
            :ripple="false" />
        </template>
        <template v-slot:body-selection="scope" >
          <q-checkbox dense v-model="scope.selected" @dblclick.stop />
        </template>
        <!--无数据提示-->
        <template v-slot:no-data>
          <div class="full-width items-center justify-center row">
            <q-icon name="error_outline" />
            {{$t('无数据')}}
            <q-btn flat
              icon="refresh" :loading="listDataLoadingState" :disable="listDataLoadingState" dense :title="$t('刷新')"
              size="sm"
              class="q-ml-sm" @click="loadListData"></q-btn>
          </div>
        </template>
        <!--标志列-->
        <template v-slot:body-cell-unreadFlag="props">
          <q-td :props="props" auto-width>
            <q-icon color="primary" name="mail" size="20px" v-if="props.row.isUnread === true" :title="$t('未读')" />
<!--            <q-icon color="grey-8" name="drafts" size="20px" v-if="props.row.isUnread === false" title="已读" />-->
            <q-icon color="primary" name="mdi-file-clock" size="20px" v-if="props.row.isNeedToHandle===true" :title="$t('待处理')"/>
<!--            <q-icon color="grey-6" name="mdi-file-check" size="20px" v-if="props.row.isNeedToHandle===false" title="已处理"/>-->
          </q-td>
        </template>
        <!--操作列-->
        <template v-slot:body-cell-operation="props">
          <q-td :props="props" auto-width>
            <q-btn :dense="true" @click="goHandleMessage(props.row)" class="btn-in-row q-mr-xs" :label="$t('前往查看')"
              color="primary" v-if="props.row.handleUrl" />
<!--            <q-btn :dense="true" @click="deleteMessage(props.row.msgUuid)" color="red" label="删除" class="btn-in-row" />-->
          </q-td>
        </template>
        <template v-slot:bottom>
          <paging-bar :loading-state="listDataLoadingState" :pageNo="fpsReq.pageNo" :pageSize="fpsReq.pageSize"
            :totalAmount="fpsInfo.totalAmount" @go-to-page="fpsNav.gotoPage"
            @pagesize-changed="fpsAssist.onPageSizeChanged" />
        </template>
      </q-table>
    </div>
    <!-- 弹出消息对话框 -->
    <q-dialog transition-hide="none" transition-show="none" v-model="openingMsgDlg">
      <q-card style="width: 800px; max-width: 80vw;">
        <q-card-section class="row items-center q-px-sm q-pt-sm q-pb-none">
          <div class="text-h6">{{$d.openingMsgItem.title}}</div>
          <q-space />
          <q-btn icon="close" flat dense v-close-popup />
        </q-card-section>
        <q-card-section class="row items-center q-px-sm q-pb-sm q-pt-none">
          <q-btn :dense="true" @click="goHandleMessage($d.openingMsgItem)" class="btn-in-row q-mr-xs" :label="$t('前往查看')"
            color="primary" v-if="$d.openingMsgItem.handleUrl" />
          <div class="text-subtitle2">{{fmt.dtFmtFull($d.openingMsgItem.occurDt)}}</div>
        </q-card-section>
        <q-separator />
        <q-card-section class="q-pa-sm">
          <q-scroll-area style="height: 206px" :visible="true">
            {{$d.openingMsgItem.content}}
          </q-scroll-area>
        </q-card-section>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script lang="ts">
export default {
  name: 'messageStd'
}
</script>
<script lang="ts" setup>
import {useFpsHelper} from '../../hooks/fpsHelper'
import {useTitleHelper} from '../../hooks/titleHelper'
import {ColumnInfo} from '../../defs/comm'
import {reactive, ref} from 'vue'
import {MessageForList, GetMessageListReq, GetMessageListResp} from '../../defs/my'
import _ from 'lodash'
import {useI18n} from 'vue-i18n'

const {t} = useI18n()

const pageTitle = t('我的消息')
useTitleHelper(pageTitle)

const fpsReq: GetMessageListReq = reactive({
  pageNo: 1,
  pageSize: 40,
  isDescending: false,
  orderBy: null,
  msgType: 'all' // 'all', 'unread', 'unhandled'
})

const columnsDefine: ColumnInfo[] = [
  {
    name: 'unreadFlag',
    label: t('标志'),
    field: 'unreadFlag',
    align: 'left',
    defOrder: 1,
    defVisible: true
  },
  {
    name: 'operation',
    label: t('操作'),
    field: 'operation',
    align: 'left',
    defOrder: 2,
    defVisible: true
  },
  {
    name: 'title',
    label: t('主题'),
    field: 'title',
    align: 'left',
    defOrder: 3,
    defVisible: true
  },
  {
    name: 'content',
    label: t('内容'),
    field: 'content',
    align: 'left',
    defOrder: 4,
    defVisible: true,
    style: 'width: 500px',
    // format: (value: string) => $f.fmt.ellipsisContent(value, 50)
  },
  {
    name: 'occurDt',
    label: t('时间'),
    field: 'occurDt',
    align: 'left',
    defOrder: 5,
    defVisible: true,
    format: (value: Date|string) => $f.fmt.dtFmtFull(value)
  }
]

const $d = reactive({
  tableData: [] as MessageForList[],
  selectedItems: [] as MessageForList[],
  // 双击打开查看的消息
  openingMsgItem: {} as MessageForList,
  listOptions: [
    {
      label: t('全部'),
      value: 'all'
    },
    {
      label: t('未读'),
      value: 'unread'
    },
    {
      label: t('待处理'),
      value: 'unhandled'
    }
  ]
})

const openingMsgDlg = ref(false)

const listDataLoadingState = ref(false)

const loadListData = function () {
  // 更新未读数量
  $f.axios.get<number>('/comm/msg/get-unread-msg-num').then((result) => {
    $d.selectedItems = []
    $f.unreadMsgNum.value = result.data
  }).catch((err) => {
    $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
  })

  listDataLoadingState.value = true
  $f.axios.get<GetMessageListResp>('/comm/msg/get-msg-list', {params: fpsReq})
    .then((result) => {
      fpsAssist.handleGenericFpsResp(result.data)
      $d.tableData = result.data.msgs
      fpsAssist.saveFpsReq(fpsReq)
    })
    .catch((err) => {
      $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
    })
    .finally(() => {
      listDataLoadingState.value = false
    })
}

// FPS配置
const {
  fpsInfo,
  fpsAssist,
  fpsNav,
  searchBarVisibility
} = useFpsHelper('/comm/my/message', null, null, null, fpsReq, columnsDefine, null, loadListData)

// // 删除单条
// const deleteMessage = function (msgUuidToDel: string) {
//   $f.axios.post('/comm/msg/delete-msg/' + msgUuidToDel)
//     .then(() => {
//       loadListData()
//     })
//     .catch((err) => {
//       $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
//     })
// }

const deleteMessages = function () {
  void $f.ui.messageBox({
    caption: t('操作确认'),
    text: t('确定要删除该选中消息吗?'),
    icon: 'Warning',
    buttons: 'OkCancel',
    delayClose: true
  }).then((btn) => {
    if (btn === 'ok') {
      $f.axios
        .post('/comm/msg/delete-msgs', _.map($d.selectedItems, 'msgUuid'))
        .then(() => {
          $f.ui.closeMsgBox()
          $d.selectedItems = []
          loadListData()
        })
        .catch((err) => {
          void $f.ui.messageBox({
            caption: t('删除失败'),
            text: $f.getAxiosErrMsg(err),
            icon: $f.getAxiosErrIcon(err),
            buttons: 'Close'
          })
        })
    }
  })
}

// 跳转去处理消息
const goHandleMessage = function (msgItem: MessageForList) {
  if (msgItem.handleUrl) {
    if (msgItem.isUnread) {
      markMsgRead(msgItem.msgUuid, false)
    }
    if (msgItem.handleUrl.startsWith($f.appCfg.websiteBaseUrl)) {
      void $f.router.push(msgItem.handleUrl.substring($f.appCfg.websiteBaseUrl.length))
    } else {
      window.location.href = msgItem.handleUrl
    }
  }
}
// 标记一条消息已读
const markMsgRead = function (msgUuid: string, reload: boolean) {
  $f.axios
    .post('/comm/msg/mark-msg-read/' + msgUuid)
    .then(() => {
      if (reload) {
        loadListData()
      }
    })
    .catch((err) => {
      $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
    })
}

// 标记全部已读
const workingStateMarkAllMsgRead = ref(false)
const markAllMsgRead = function () {
  workingStateMarkAllMsgRead.value = true
  $f.axios
    .post('/comm/msg/mark-all-msg-read')
    .then(() => {
      loadListData()
    })
    .catch((err) => {
      $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
    })
    .finally(() => {
      workingStateMarkAllMsgRead.value = false
    })
}

// 清空消息
const deleteReadAndHandleMessages = function () {
  void $f.ui.messageBox({
    caption: t('操作确认'),
    text: t('确认要清空所有已读并已处理的消息吗?'),
    icon: 'Warning',
    buttons: 'OkCancel',
    delayClose: true
  }).then((btn) => {
    if (btn === 'ok') {
      $f.axios
        .post('/comm/msg/delete-all-msg?readmsg=true&handledmsg=true')
        .then(() => {
          loadListData()
          $f.ui.closeMsgBox()
        })
        .catch((err) => {
          void $f.ui.messageBox({
            caption: t('操作失败'),
            text: $f.getAxiosErrMsg(err),
            icon: $f.getAxiosErrIcon(err),
            buttons: 'Close'
          })
        })
    }
  })
}

const onRowDblClick = function (evt: MouseEvent, row: MessageForList) {
  $d.openingMsgItem = row
  openingMsgDlg.value = true
  if (row.isUnread) {
    markMsgRead(row.msgUuid, true)
  }
}

const fmt = $f.fmt

</script>

<style lang="sass" scoped>
.primary-color-border
  border: 1px solid $primary
</style>
